//
//  C15BlockConcurrentTasks.m
//  精通Objective-C
//
//  Created by 花强 on 2017/12/28.
//  Copyright © 2017年 花强. All rights reserved.
//

#import "C15BlockConcurrentTasks.h"

#define YahooURL @"http://www.yahoo.com/index.html"
#define ApressURL @"http://www.apress.com/index.html"

typedef void (^DownloadURL)(void);

@implementation C15BlockConcurrentTasks

DownloadURL getDownloadURLBlock(NSString * url){
    NSString * urlString = url;
    return ^{
        NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
        NSError * error;
        NSDate * startTime = [NSDate date];
        NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
        if (data == nil) {
            NSLog(@"Error %@",[error localizedDescription]);
        }else{
            NSDate * endTime = [NSDate date];
            NSTimeInterval timeInterval = [endTime timeIntervalSinceDate:startTime];
            NSLog(@"Time takes %f seconds,for url %@",timeInterval,urlString);
        }
    };
}

-(void)testBlockConcurrentTasks{
    //创建任务请求
    dispatch_queue_t queue1 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_queue_t queue2 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    if (queue1 == queue2) {
        NSLog(@"=========");
    }
    //创建任务分组
    dispatch_group_t group = dispatch_group_create();
    
    //获取当前时间
    NSDate * startTime = [NSDate date];
    
    //创建并分派异步任务
    dispatch_group_async(group, queue1, getDownloadURLBlock(YahooURL));
    dispatch_group_async(group, queue2, getDownloadURLBlock(ApressURL));

    //等待，直到分组中的所有任务完成为止
    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
    
    NSDate * endTime = [NSDate date];
    NSTimeInterval timeInterval = [endTime timeIntervalSinceDate:startTime];
    NSLog(@"Time takes %f seconds,for all urls",timeInterval);
}

@end
